

import threading,time,itchat
from datetime import datetime
from itchat.content import *
from config import config

class App(object):
    '''应用程序'''
    # 程序状态量：
    status_dict = {
        "WAIT":'状态：请输入指令',
        "PEND":'状态：请输入内容或参数',
        "CLOSE":'状态：程序已关闭',
    }

    INFO_TIP = "【提示消息】\n"
    APP_TIP = "【应用消息】\n"
    USER_TIP = "【用户消息】\n"

    status = ''
    status_ch = ''
    _start_timestamp = 0
    last_command = ''
    chat = None
    handel_open = True

    def __init__(self):
        self.status = 'WAIT'
        self.status_ch = self.status_dict['WAIT']
        self._start_timestamp = time.time()
        self.chat = itchat

    _instance_lock = threading.Lock()

    @classmethod
    def instance(cls, *args, **kwargs):
        ''' 线程安全的单例（加锁的，未加锁部分并发执行,加锁部分串行执行,速度降低,保证了数据安全）'''
        with App._instance_lock:
            if not hasattr(App, "_instance"):
                App._instance = App(*args, **kwargs)
        return App._instance

    def getconfig(self, configname):
        '''获取配置信息'''
        return config[str(configname)]

    def getRunningTimeStr(self):
        '''运行时间字符串（分钟）'''
        nowtimestemp = time.time()
        runningtime = nowtimestemp - self._start_timestamp
        return str(int(runningtime / 60)) + '分钟'

    def run(self, debug=True, *args, **kwargs):
        '''开始运行''' 
        # 登录
        self.chat.auto_login(*args, **kwargs)
        self.loginSuccessPrint()
        self.chat.run(debug)

        
    def start(self):
        '''开始操作，开启消息监听处理'''
        self.handel_open = True
        self.status = 'WAIT'
        self.status_ch = self.status_dict['WAIT']
        
    
    def close(self):
        '''关闭操作，关闭消息监听'''
        self.handel_open = False
        self.status = 'CLOSE'
        self.status_ch = self.status_dict['CLOSE']

    def gotowait(self, msg):
        '''跳入等待输入指令状态'''
        self.status = 'WAIT'
        self.status_ch = self.status_dict['WAIT']
        self.msgPrint(msg)

    def gotopend(self, msg):
        '''跳入等待输入参数状态'''
        self.status = 'PEND'
        self.status_ch = self.status_dict['PEND']
        self.msgPrint(msg, tips=False)

    def msgPrint(self, msg, toUserName='filehelper', tips = True):
        '''消息回复的底层方法'''
        self.chat.send(str(msg), toUserName)
        if (toUserName == 'filehelper' and tips):
            self.msgTips()
    
    def msgTips(self, toUserName='filehelper'):
        '''提示消息'''
        self.chat.send(self.INFO_TIP + str(self.status_ch), toUserName)

    def printHelpInfo(self):
        '''回复帮助消息'''
        self.msgPrint(self.APP_TIP + self.getconfig('help_info'), tips=False)
    
    def printRuntimeInfo(self):
        '''回复运行时间消息'''
        self.msgPrint(self.APP_TIP + '已运行:' + self.getRunningTimeStr(), tips=False)

    def loginSuccessPrint(self):
        '''登录成功的消息提示'''
        nowtimestemp = time.localtime()
        nowtimestr = time.strftime("%Y-%m-%d %H:%M:%S", nowtimestemp)
        self.msgPrint(self.APP_TIP + '登录成功:' + nowtimestr)

    def __str__(self):
        return 'App Obj'

    def __del__(self):
        '''析构'''
        pass

# (模块模式)单例对象
# app = App()
# 外部调用 from App import app
